package org.jeecg.modules.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.oms.entity.*;
import org.jeecg.modules.oms.mapper.DesignFileMapper;
import org.jeecg.modules.oms.mapper.ProductSalesOrderDetailMapper;
import org.jeecg.modules.oms.mapper.ProductSalesOrderMapper;
import org.jeecg.modules.oms.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jeecg.modules.oms.vo.SummaryFileParseResultVO;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 设计文件Service实现
 */
@Slf4j
@Service
public class DesignFileServiceImpl extends ServiceImpl<DesignFileMapper, DesignFile> implements IDesignFileService {

    @Value("${jeecg.path.upload}")
    private String uploadPath;

    @Autowired
    private ProductSalesOrderMapper productSalesOrderMapper;

    @Autowired
    private ProductSalesOrderDetailMapper productSalesOrderDetailMapper;

    @Autowired
    private ICfProfileSizeTableService cfProfileSizeTableService;

    @Autowired
    private ICfGlassSizeTableService cfGlassSizeTableService;

    @Autowired
    private ICfAccessoriesTableService cfAccessoriesTableService;

    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    private IXgeProfileSizeTableService xgeProfileSizeTableService;

    @Autowired
    private IXgeGlassSizeTableService xgeGlassSizeTableService;

    @Autowired
    private IXgeAccessoriesTableService xgeAccessoriesTableService;

    @Override
    public DesignFile getByOrderId(String orderId) {
        if (StringUtils.isBlank(orderId)) {
            return null;
        }

        LambdaQueryWrapper<DesignFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DesignFile::getOrderId, orderId);
        return getOne(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean uploadSummaryFile(String orderId, MultipartFile file, String uploadPersonId, String uploadPersonName) {
        if (StringUtils.isBlank(orderId)) {
            throw new JeecgBootException("订单ID不能为空");
        }

        if (file == null || file.isEmpty()) {
            throw new JeecgBootException("文件不能为空");
        }

        // 获取订单信息，确认订单存在
        ProductSalesOrder order = productSalesOrderMapper.selectById(orderId);
        if (order == null) {
            throw new JeecgBootException("未找到对应订单");
        }

        try {
            // 上传路径：upload/order/summary/年月/订单ID_文件名.扩展名
            Calendar calendar = Calendar.getInstance();
            String year = String.valueOf(calendar.get(Calendar.YEAR));
            String month = String.format("%02d", calendar.get(Calendar.MONTH) + 1);
            String relativePath = "order/summary/" + year + month;
            String absolutePath = uploadPath + File.separator + relativePath;

            // 创建目录
            File saveDir = new File(absolutePath);
            if (!saveDir.exists() && !saveDir.mkdirs()) {
                throw new JeecgBootException("创建文件目录失败:" + absolutePath);
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = FilenameUtils.getExtension(originalFilename);
            String saveFileName = orderId + "_" + UUIDGenerator.generate() + "." + fileExtension;
            String savePath = absolutePath + File.separator + saveFileName;

            // 保存文件
            File saveFile = new File(savePath);
            try {
                file.transferTo(saveFile);
                log.info("汇总单上传成功，保存路径：{}", savePath);
            } catch (IOException e) {
                log.error("汇总单上传失败", e);
                throw new JeecgBootException("文件上传失败", e);
            }

            // 保存文件记录
            String fileRelativePath = relativePath + File.separator + saveFileName;
            DesignFile designFile = getByOrderId(orderId);
            if (designFile == null) {
                designFile = new DesignFile();
                designFile.setOrderId(orderId);
                designFile.setSummaryFileName(originalFilename);
                designFile.setSummaryFilePath(fileRelativePath);
                designFile.setUploadSummaryPersonId(uploadPersonId);
                designFile.setUploadSummaryPersonName(uploadPersonName);
                designFile.setUploadSummaryTime(new Date());
                designFile.setUploadPersonId(uploadPersonId);
                designFile.setUploadPersonName(uploadPersonName);
                designFile.setUploadTime(new Date());
                return save(designFile);
            } else {
                // 如果已有记录，则更新
                designFile.setSummaryFileName(originalFilename);
                designFile.setSummaryFilePath(fileRelativePath);
                designFile.setUploadSummaryPersonId(uploadPersonId);
                designFile.setUploadSummaryPersonName(uploadPersonName);
                designFile.setUploadSummaryTime(new Date());
                designFile.setUploadPersonId(uploadPersonId);
                designFile.setUploadPersonName(uploadPersonName);
                designFile.setUploadTime(new Date());
                return updateById(designFile);
            }
        } catch (Exception e) {
            if (!(e instanceof JeecgBootException)) {
                log.error("汇总单上传失败", e);
            }
            throw new JeecgBootException("汇总单上传失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean uploadOptimizationFile(String orderId, MultipartFile file, String uploadPersonId, String uploadPersonName) {
        if (StringUtils.isBlank(orderId)) {
            throw new JeecgBootException("订单ID不能为空");
        }

        if (file == null || file.isEmpty()) {
            throw new JeecgBootException("文件不能为空");
        }

        try {
            // 上传路径：upload/order/optimization/年月/订单ID_文件名.扩展名
            Calendar calendar = Calendar.getInstance();
            String year = String.valueOf(calendar.get(Calendar.YEAR));
            String month = String.format("%02d", calendar.get(Calendar.MONTH) + 1);
            String relativePath = "order/optimization/" + year + month;
            String absolutePath = uploadPath + File.separator + relativePath;

            // 创建目录
            File saveDir = new File(absolutePath);
            if (!saveDir.exists() && !saveDir.mkdirs()) {
                throw new JeecgBootException("创建文件目录失败:" + absolutePath);
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = FilenameUtils.getExtension(originalFilename);
            String saveFileName = orderId + "_" + UUIDGenerator.generate() + "." + fileExtension;
            String savePath = absolutePath + File.separator + saveFileName;

            // 保存文件
            File saveFile = new File(savePath);
            try {
                file.transferTo(saveFile);
                log.info("优化单上传成功，保存路径：{}", savePath);
            } catch (IOException e) {
                log.error("优化单上传失败", e);
                throw new JeecgBootException("文件上传失败", e);
            }

            // 保存文件记录
            String fileRelativePath = relativePath + File.separator + saveFileName;

            String[] split = orderId.split(",");
            for (String id : split){
                DesignFile designFile = getByOrderId(id);
                if (designFile == null) {
                    designFile = new DesignFile();
                    designFile.setOrderId(orderId);
                    designFile.setOptimizationFileName(originalFilename);
                    designFile.setOptimizationFilePath(fileRelativePath);
                    designFile.setUploadOptimizationPersonId(uploadPersonId);
                    designFile.setUploadOptimizationPersonName(uploadPersonName);
                    designFile.setUploadOptimizationTime(new Date());
                    designFile.setUploadPersonId(uploadPersonId);
                    designFile.setUploadPersonName(uploadPersonName);
                    designFile.setUploadTime(new Date());
                    save(designFile);
                } else {
                    // 如果已有记录，则更新
                    designFile.setOptimizationFileName(originalFilename);
                    designFile.setOptimizationFilePath(fileRelativePath);
                    designFile.setUploadOptimizationPersonId(uploadPersonId);
                    designFile.setUploadOptimizationPersonName(uploadPersonName);
                    designFile.setUploadOptimizationTime(new Date());
                    designFile.setUploadPersonId(uploadPersonId);
                    designFile.setUploadPersonName(uploadPersonName);
                    designFile.setUploadTime(new Date());
                    updateById(designFile);
                }
            }
        } catch (Exception e) {
            if (!(e instanceof JeecgBootException)) {
                log.error("优化单上传失败", e);
            }
            throw new JeecgBootException("优化单上传失败: " + e.getMessage());
        }
        return true;
    }

    @Override
    public List<DesignFile> getRecentFiles(int limit) {
        Page<DesignFile> page = new Page<>(1, limit);
        LambdaQueryWrapper<DesignFile> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(DesignFile::getUpdateTime);
        return page(page, queryWrapper).getRecords();
    }

    @Override
    public List<DesignFile> getRecentFiles(Map<String, Object> params) {
        log.info("获取最近设计文件，参数: {}", params);

        // 获取分页参数
        Integer limit = params.get("limit") != null ? Integer.parseInt(params.get("limit").toString()) : 10;
        Page<DesignFile> page = new Page<>(1, limit);

        // 构建查询条件
        LambdaQueryWrapper<DesignFile> queryWrapper = new LambdaQueryWrapper<>();

        // 订单编号查询
        String orderNo = (String) params.get("orderNo");
        if (StringUtils.isNotBlank(orderNo)) {
            // 联表查询订单编号
            queryWrapper.inSql(DesignFile::getOrderId,
                    "SELECT id FROM oms_product_sales_order WHERE order_no LIKE '%" + orderNo + "%'");
        }

        // 文件类型查询
        String fileType = (String) params.get("fileType");
        if (StringUtils.isNotBlank(fileType)) {
            if ("summary".equals(fileType)) {
                queryWrapper.isNotNull(DesignFile::getSummaryFilePath);
                queryWrapper.isNull(DesignFile::getOptimizationFilePath);
            } else if ("optimization".equals(fileType)) {
                queryWrapper.isNotNull(DesignFile::getOptimizationFilePath);
                queryWrapper.isNull(DesignFile::getSummaryFilePath);
            } else if ("both".equals(fileType)) {
                queryWrapper.isNotNull(DesignFile::getSummaryFilePath);
                queryWrapper.isNotNull(DesignFile::getOptimizationFilePath);
            }
        }

        // 上传人查询
        String uploadPerson = (String) params.get("uploadPerson");
        if (StringUtils.isNotBlank(uploadPerson)) {
            queryWrapper.and(wrapper -> wrapper
                    .eq(DesignFile::getUploadSummaryPersonId, uploadPerson)
                    .or()
                    .eq(DesignFile::getUploadOptimizationPersonId, uploadPerson));
        }

        // 上传日期范围查询
        String beginDate = (String) params.get("beginDate");
        String endDate = (String) params.get("endDate");
        if (StringUtils.isNotBlank(beginDate)) {
            queryWrapper.and(wrapper -> wrapper
                    .ge(DesignFile::getUploadSummaryTime, beginDate + " 00:00:00")
                    .or()
                    .ge(DesignFile::getUploadOptimizationTime, beginDate + " 00:00:00"));
        }
        if (StringUtils.isNotBlank(endDate)) {
            queryWrapper.and(wrapper -> wrapper
                    .le(DesignFile::getUploadSummaryTime, endDate + " 23:59:59")
                    .or()
                    .le(DesignFile::getUploadOptimizationTime, endDate + " 23:59:59"));
        }

        // 按更新时间倒序
        queryWrapper.orderByDesc(DesignFile::getUpdateTime);

        // 执行查询
        List<DesignFile> designFiles = page(page, queryWrapper).getRecords();

        // 填充订单编号信息
        if (designFiles != null && !designFiles.isEmpty()) {
            for (DesignFile designFile : designFiles) {
                if (StringUtils.isNotBlank(designFile.getOrderId())) {
                    ProductSalesOrder order = productSalesOrderMapper.selectById(designFile.getOrderId());
                    if (order != null) {
                        designFile.setOrderNo(order.getOrderNo());
                    }
                }
            }
        }

        return designFiles;
    }

    /**
     * 新格尔上传窗户、门的汇总单解析
     * @param file 上传的Excel文件
     * @param orderId 订单ID
     * @param tenantId 租户ID
     * @param windowDoorType
     * @return
     */
    @Override
    public SummaryFileParseResultVO parseSummaryExcelFile(MultipartFile file, String orderId, Integer tenantId, Integer windowDoorType) {
        log.info("开始解析汇总单Excel文件，orderId={}, tenantId={}", orderId, tenantId);

        SummaryFileParseResultVO result = new SummaryFileParseResultVO();
        result.setSuccess(false);
        result.setOrderId(orderId);
        result.setTenantId(tenantId);

        InputStream inputStream = null;
        Workbook workbook = null;

        try {
            // 获取订单信息，确认优化软件类型
            ProductSalesOrder order = productSalesOrderMapper.selectById(orderId);
            if (order != null && order.getOptimizationSoftwareType() != null) {
                result.setOptimizeSoftType(order.getOptimizationSoftwareType());
            } else {
                // 默认为新格尔类型
                result.setOptimizeSoftType(0);
            }


            // 打开Excel文件
            inputStream = file.getInputStream();

            try {
                if (file.getOriginalFilename().endsWith("xlsx")) {
                    workbook = new XSSFWorkbook(inputStream);
                } else {
                    workbook = new HSSFWorkbook(inputStream);
                }
            } catch (Exception e) {
                log.error("无法打开Excel文件", e);
                result.setMessage("无法打开Excel文件: " + e.getMessage());
                return result;
            }

            // 根据门窗类型选择不同的处理方式
            if (windowDoorType == 0) {
                // 提取订单基本信息（订单号、客户名称等）
                extractOrderInfoForWindow(workbook, result);
                // 如果没有成功提取订单号，返回失败
                if (StringUtils.isBlank(result.getOrderNo())) {
                    result.setMessage("无法从汇总单中提取订单号信息");
                    return result;
                }
                // 处理窗户文件
                dealWindowFile(workbook, result, orderId, tenantId);
            }
//            else {
//                // 提取订单基本信息（订单号、客户名称等）
//                extractOrderInfoForDoor(workbook, result);
//                if (StringUtils.isBlank(result.getOrderNo())) {
//                    result.setMessage("无法从汇总单中提取订单号信息");
//                    return result;
//                }
//                // 返回的是订单明细编号
//                //要根据订单明细编号查询订单编号  若订单不存在，则返回
//                ProductSalesOrderDetail productSalesOrderDetail = productSalesOrderDetailMapper.selectOne(new LambdaQueryWrapper<ProductSalesOrderDetail>().eq(
//                        ProductSalesOrderDetail::getId, result.getOrderNo().split(",")[0]));
//                if (productSalesOrderDetail == null || !productSalesOrderDetail.getOrderId().equals(orderId)) {
//                    result.setMessage("无法从汇总单中提取订单号信息");
//                    return result;
//                }
//
//                // 处理门文件
//                dealDoorFile(workbook, result, orderId, tenantId);
//            }

            // 检查是否提取到数据
            if ((result.getXgeProfileList() == null || result.getXgeProfileList().isEmpty()) &&
                    (result.getXgeGlassList() == null || result.getXgeGlassList().isEmpty()) &&
                    (result.getXgeAccessoriesList() == null || result.getXgeAccessoriesList().isEmpty())) {
                result.setMessage("未能从Excel中提取到型材、玻璃或配件数据");
                return result;
            }

            // 提取成功
            result.setSuccess(true);
            result.setMessage("汇总单解析成功");

            log.info("汇总单解析成功，型材：{}条，玻璃：{}条，配件：{}条",
                    result.getProfileCount(),
                    result.getGlassCount(),
                    result.getAccessoriesCount());

            return result;
        } catch (Exception e) {
            log.error("解析汇总单Excel文件失败", e);
            result.setMessage("解析汇总单Excel文件失败: " + e.getMessage());
            return result;
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception e) {
                log.error("关闭文件流失败", e);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processSummaryFileResult(SummaryFileParseResultVO result, String orderId,
                                            MultipartFile file, String uploadPersonId, String uploadPersonName) {
        if (result == null) {
            log.error("解析结果为空或解析失败，无法保存");
            return false;
        }

        try {
            // 1. 先删除已有的数据
            deleteExistingData(orderId);

            // 判断优化软件类型
            Integer optimizeSoftType = result.getOptimizeSoftType();
            if (optimizeSoftType == null) {
                // 默认为新格尔类型
                optimizeSoftType = 1;
                result.setOptimizeSoftType(optimizeSoftType);
            }

            // 保存型材数据
            if (result.getXgeProfileList() != null && !result.getXgeProfileList().isEmpty()) {
                xgeProfileSizeTableService.saveBatch(result.getXgeProfileList());
            }

            // 保存玻璃数据
            if (result.getXgeGlassList() != null && !result.getXgeGlassList().isEmpty()) {
                xgeGlassSizeTableService.saveBatch(result.getXgeGlassList());
            }

            // 保存配件数据
            if (result.getXgeAccessoriesList() != null && !result.getXgeAccessoriesList().isEmpty()) {
                xgeAccessoriesTableService.saveBatch(result.getXgeAccessoriesList());
            }

            // 上传汇总单文件
            boolean fileUploaded = uploadSummaryFile(orderId, file, uploadPersonId, uploadPersonName);
            if (!fileUploaded) {
                log.error("上传汇总单文件失败");
                throw new JeecgBootException("上传汇总单文件失败");
            }

            return true;
        } catch (Exception e) {
            log.error("保存汇总单解析结果失败", e);
            throw new JeecgBootException("保存汇总单解析结果失败: " + e.getMessage());
        }
    }

    /**
     * 删除已有的型材、玻璃和配件数据
     */
    private void deleteExistingData(String orderId) {
        log.info("删除订单已有的型材、玻璃和配件数据, orderId={}", orderId);

        // 查找该订单关联的所有订单明细ID
        List<String> detailIds = baseMapper.getOrderDetailIds(orderId);
        if (detailIds == null || detailIds.isEmpty()) {
            log.info("订单没有关联的明细数据, orderId={}", orderId);
            return;
        }

        // 根据订单明细ID删除相关数据
        for (String detailId : detailIds) {
            // 删除新格尔数据
            xgeProfileSizeTableService.deleteByDetailId(detailId);
            xgeGlassSizeTableService.deleteByDetailId(detailId);
            xgeAccessoriesTableService.deleteByDetailId(detailId);
        }

        log.info("已删除订单关联的所有型材、玻璃和配件数据, orderId={}, detailCount={}", orderId, detailIds.size());
    }

    /**
     * 从Excel中提取订单基本信息（订单号、客户名称等）
     */
    private void extractOrderInfoForWindow(Workbook workbook, SummaryFileParseResultVO result) {
        log.info("开始提取订单基本信息");

        // 通常订单基本信息在第一个Sheet的前几行
        Sheet sheet = workbook.getSheetAt(0);
        String orderNo = null;

        // 检查前20行
        for (int i = 0; i < 20 && i < sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;

            for (int j = 0; j < row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j);
                if (cell == null) continue;

                String cellValue = getCellValueAsString(cell);
                if (StringUtils.isBlank(cellValue)) continue;

                // 查找可能包含订单号的行
                if (cellValue.contains("订单号") || cellValue.contains("合同号") || cellValue.contains("订单编号")) {
                    // 尝试从相邻的单元格获取订单号
                    orderNo = extractValueFromAdjacentCells(row, j);
                    break;
                }
            }
            if (orderNo != null) {
                break;
            }
        }

        // 设置结果
        result.setOrderNo(orderNo);
    }

    /**
     * 从相邻单元格获取值
     * 对于订单号/合同号的提取，会从当前单元格向右查找第一个有数据的单元格
     */
    private String extractValueFromAdjacentCells(Row row, int cellIndex) {
        log.debug("开始从第{}行，第{}列后查找数据", row.getRowNum(), cellIndex);

        // 向右查找，找到第一个有数据的单元格
        for (int i = cellIndex + 1; i < row.getLastCellNum(); i++) {
            Cell cell = row.getCell(i);
            if (cell != null) {
                String value = getCellValueAsString(cell);
                log.debug("检查单元格[{},{}]，值为：{}", row.getRowNum(), i, value);
                if (StringUtils.isNotBlank(value)) {
                    log.debug("在[{},{}]找到非空值: {}", row.getRowNum(), i, value);
                    return value.trim();
                }
            }
        }

        log.debug("未找到有效数据");
        return null;
    }

    /**
     * 获取单元格值的字符串形式
     */
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return DateUtils.formatDate(cell.getDateCellValue(), "yyyy-MM-dd");
                } else {
                    return String.valueOf((int) cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                try {
                    return String.valueOf(cell.getStringCellValue());
                } catch (Exception e) {
                    try {
                        return String.valueOf(cell.getNumericCellValue());
                    } catch (Exception ex) {
                        return "";
                    }
                }
            default:
                return "";
        }
    }

    /**
     * 从Excel中提取新格尔型材数据
     */
    private List<XgeProfileSizeTable> extractXgeProfileData(Workbook workbook, SummaryFileParseResultVO result,
                                                            String orderId, Integer tenantId) {
        log.info("开始提取新格尔型材数据, orderId={}", orderId);

        // 获取订单明细ID
        ConcurrentHashMap<String, String> detailIdMap = new ConcurrentHashMap<>();

        // 创建线程安全的集合
        List<XgeProfileSizeTable> profileList = Collections.synchronizedList(new ArrayList<>());

        try {
            // 默认使用第一个Sheet
            Sheet profileSheet = workbook.getSheetAt(0);
            int sheetIndex = 0;

            log.info("使用第一个Sheet提取型材数据: index={}, name={}", sheetIndex, profileSheet.getSheetName());

            // 找到型材标题行 窗号	编号	名称	颜色	切角	长度	数量
            int headerRowIndex = findHeaderRow(profileSheet, new String[]{"窗号", "编号", "名称", "颜色", "切角", "长度", "数量"});
            if (headerRowIndex < 0) {
                log.warn("未找到型材数据标题行");
                return profileList;
            }

            // 解析标题行，找到各列对应的索引
            Row headerRow = profileSheet.getRow(headerRowIndex);
            Map<String, Integer> columnIndexMap = new HashMap<>();

            for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell != null) {
                    String headerValue = getCellValueAsString(cell);
                    if (StringUtils.isNotBlank(headerValue)) {
                        if (headerValue.contains("窗号")) {
                            columnIndexMap.put("windowNo", i);
                        } else if (headerValue.contains("编号")) {
                            columnIndexMap.put("profileCode", i);
                        } else if (headerValue.contains("名称")) {
                            columnIndexMap.put("profileName", i);
                        } else if (headerValue.contains("颜色")) {
                            columnIndexMap.put("color", i);
                        } else if (headerValue.contains("切角")) {
                            columnIndexMap.put("cutAngle", i);
                        } else if (headerValue.contains("长度")) {
                            columnIndexMap.put("length", i);
                        } else if (headerValue.contains("数量")) {
                            columnIndexMap.put("quantity", i);
                        }
                    }
                }
            }

            // 检查是否找到必要的列
            if (!columnIndexMap.containsKey("profileName") && !columnIndexMap.containsKey("profileCode")) {
                log.warn("型材数据中没有找到必要的列：型材代码或型材名称");
                return profileList;
            }

            // 提取数据行
            int dataRowIndex = headerRowIndex + 1;
            // 使用AtomicInteger保证线程安全
            final AtomicInteger serialNo = new AtomicInteger(1);

            // 读取数据直到找到"合计"行或者到达最后一行
            while (dataRowIndex <= profileSheet.getLastRowNum()) {
                Row dataRow = profileSheet.getRow(dataRowIndex);
                dataRowIndex++;

                if (dataRow == null) {
                    continue;
                }

                // 检查是否是空行
                boolean isEmptyRow = true;
                for (int i = 0; i < dataRow.getLastCellNum(); i++) {
                    Cell cell = dataRow.getCell(i);
                    if (cell != null && StringUtils.isNotBlank(getCellValueAsString(cell))) {
                        isEmptyRow = false;
                        break;
                    }
                }

                if (isEmptyRow) {
                    continue;
                }

                // 检查是否到达"合计"行
                Cell firstCell = dataRow.getCell(0);
                if (firstCell != null) {
                    String firstCellValue = getCellValueAsString(firstCell);
                    if (StringUtils.isNotBlank(firstCellValue) && firstCellValue.contains("合计")) {
                        log.info("型材数据提取到达合计行，停止提取");
                        break;
                    }
                }

                // 提取单元格数据  窗号	编号		名称		颜色			切角			长度				数量
                XgeProfileSizeTable profile = new XgeProfileSizeTable();
                profile.setId(UUIDGenerator.generate());
                profile.setTenantId(tenantId);
                profile.setSerialNo(serialNo.getAndIncrement());
                //设置窗号
                if (columnIndexMap.containsKey("windowNo")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("windowNo"));
                    profile.setWindowNo(getCellValueAsString(cell));
                    if (detailIdMap.containsKey(orderId + "-" + getCellValueAsString(cell))) {
                        profile.setDetailId(detailIdMap.get(orderId + "-" + getCellValueAsString(cell)));
                    } else {
                        String detailId = getOrCreateDetailId(orderId, profile.getWindowNo());
                        detailIdMap.put(orderId + "-" + getCellValueAsString(cell), detailId);
                        profile.setDetailId(detailId);
                    }
                }

                // 设置型材代码
                if (columnIndexMap.containsKey("profileCode")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("profileCode"));
                    profile.setProfileCode(getCellValueAsString(cell));
                }

                // 设置型材名称
                if (columnIndexMap.containsKey("profileName")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("profileName"));
                    profile.setProfileName(getCellValueAsString(cell));
                }

                //设置颜色
                if (columnIndexMap.containsKey("color")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("color"));
                    profile.setColor(getCellValueAsString(cell));
                }

                // 获取切角
                if (columnIndexMap.containsKey("cutAngle")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("cutAngle"));
                    profile.setCutAngle(getCellValueAsString(cell));
                }

                // 设置长度
                if (columnIndexMap.containsKey("length")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("length"));
                    String lengthStr = getCellValueAsString(cell);
                    try {
                        profile.setLength(Double.parseDouble(lengthStr));
                    } catch (NumberFormatException e) {
                        profile.setLength(0.0);
                    }
                }

                // 设置数量
                if (columnIndexMap.containsKey("quantity")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("quantity"));
                    String quantityStr = getCellValueAsString(cell);
                    try {
                        profile.setQuantity(Integer.parseInt(quantityStr));
                    } catch (NumberFormatException e) {
                        profile.setQuantity(1);
                    }
                }

                // 设置创建和更新信息
                Date now = new Date();
                profile.setCreateTime(now);
                profile.setUpdateTime(now);

                // 如果型材代码和名称都为空，则跳过
                if (StringUtils.isBlank(profile.getProfileCode()) && StringUtils.isBlank(profile.getProfileName())) {
                    continue;
                }

                synchronized (profileList) {
                    profileList.add(profile);
                }
            }

            log.info("提取新格尔型材数据完成，共{}条记录", profileList.size());
            return profileList;
        } catch (Exception e) {
            log.error("提取新格尔型材数据失败", e);
            return profileList;
        }
    }

    /**
     * 从Excel中提取新格尔玻璃尺寸数据
     */
    private List<XgeGlassSizeTable> extractXgeGlassData(Workbook workbook, SummaryFileParseResultVO result,
                                                        String orderId, Integer tenantId) {
        log.info("开始提取新格尔玻璃数据, orderId={}", orderId);

        // 获取订单明细ID
        ConcurrentHashMap<String, String> detailIdMap = new ConcurrentHashMap<>();

        List<XgeGlassSizeTable> glassList = new ArrayList<>();

        try {
            // 默认使用第一个Sheet
            Sheet glassSheet = workbook.getSheetAt(0);
            int sheetIndex = 0;

            log.info("使用第一个Sheet提取玻璃数据: index={}, name={}", sheetIndex, glassSheet.getSheetName());

            // 找到标题行 窗号	名称	规格	安装位置	磨砂	宽	高	数量	面积	
            int headerRowIndex = findHeaderRow(glassSheet, new String[]{"窗号", "名称", "规格", "安装位置", "磨砂", "宽", "高", "数量", "面积"});
            if (headerRowIndex < 0) {
                log.warn("未找到玻璃数据标题行");
                return glassList;
            }

            // 解析标题行，找到各列对应的索引
            Row headerRow = glassSheet.getRow(headerRowIndex);
            Map<String, Integer> columnIndexMap = new HashMap<>();

            for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell != null) {
                    String headerValue = getCellValueAsString(cell);
                    if (StringUtils.isNotBlank(headerValue)) {
                        if (headerValue.contains("窗号")) {
                            columnIndexMap.put("windowNo", i);
                        } else if (headerValue.contains("名称")) {
                            columnIndexMap.put("glassName", i);
                        } else if (headerValue.contains("规格")) {
                            columnIndexMap.put("specification", i);
                        } else if (headerValue.contains("安装位置")) {
                            columnIndexMap.put("installPosition", i);
                        } else if (headerValue.contains("磨砂")) {
                            columnIndexMap.put("frosted", i);
                        } else if (headerValue.contains("宽")) {
                            columnIndexMap.put("glassWidth", i);
                        } else if (headerValue.contains("高")) {
                            columnIndexMap.put("glassHeight", i);
                        } else if (headerValue.contains("数量")) {
                            columnIndexMap.put("quantity", i);
                        } else if (headerValue.contains("面积")) {
                            columnIndexMap.put("area", i);
                        } else if (headerValue.contains("种类") || headerValue.contains("类型")) {
                            columnIndexMap.put("glassType", i);
                        }
                    }
                }
            }

            // 检查是否找到必要的列
            boolean hasDimensions = columnIndexMap.containsKey("glassWidth") && columnIndexMap.containsKey("glassHeight");
            boolean hasBasicInfo = columnIndexMap.containsKey("windowNo") || columnIndexMap.containsKey("glassName");

            if (!hasDimensions) {
                log.warn("玻璃数据中没有找到必要的列：宽或高");
                return glassList;
            }

            if (!hasBasicInfo) {
                log.warn("玻璃数据中没有找到基本信息列：窗号或名称");
            }

            // 提取数据行
            int dataRowIndex = headerRowIndex + 1;
            int serialNo = 1;

            // 读取数据直到找到"合计"行或者到达最后一行
            while (dataRowIndex <= glassSheet.getLastRowNum()) {
                Row dataRow = glassSheet.getRow(dataRowIndex);
                dataRowIndex++;

                if (dataRow == null) {
                    continue;
                }

                // 检查是否是空行
                boolean isEmptyRow = true;
                for (int i = 0; i < dataRow.getLastCellNum(); i++) {
                    Cell cell = dataRow.getCell(i);
                    if (cell != null && StringUtils.isNotBlank(getCellValueAsString(cell))) {
                        isEmptyRow = false;
                        break;
                    }
                }

                if (isEmptyRow) {
                    continue;
                }

                // 检查是否到达"合计"行
                Cell firstCell = dataRow.getCell(0);
                if (firstCell != null) {
                    String firstCellValue = getCellValueAsString(firstCell);
                    if (StringUtils.isNotBlank(firstCellValue) && firstCellValue.contains("合计")) {
                        log.info("玻璃数据提取到达合计行，停止提取");
                        break;
                    }
                }

                // 提取单元格数据
                XgeGlassSizeTable glass = new XgeGlassSizeTable();
                glass.setId(UUIDGenerator.generate());
                glass.setTenantId(tenantId);
                glass.setSerialNo(serialNo++);

                // 设置窗号
                if (columnIndexMap.containsKey("windowNo")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("windowNo"));
                    glass.setWindowNo(getCellValueAsString(cell));
                    if (detailIdMap.containsKey(orderId + "-" + getCellValueAsString(cell))) {
                        glass.setDetailId(detailIdMap.get(orderId + "-" + getCellValueAsString(cell)));
                    } else {
                        String detailId = getOrCreateDetailId(orderId, glass.getWindowNo());
                        detailIdMap.put(orderId + "-" + getCellValueAsString(cell), detailId);
                        glass.setDetailId(detailId);
                    }
                }

                // 设置玻璃名称
                if (columnIndexMap.containsKey("glassName")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("glassName"));
                    glass.setGlassName(getCellValueAsString(cell));
                }

                // 设置规格
                if (columnIndexMap.containsKey("specification")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("specification"));
                    glass.setSpecification(getCellValueAsString(cell));
                }

                // 设置安装位置
                if (columnIndexMap.containsKey("installPosition")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("installPosition"));
                    glass.setInstallPosition(getCellValueAsString(cell));
                }

                // 设置磨砂
                if (columnIndexMap.containsKey("frosted")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("frosted"));
                    glass.setFrosted(getCellValueAsString(cell));
                }

                // 设置玻璃宽度
                if (columnIndexMap.containsKey("glassWidth")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("glassWidth"));
                    String widthStr = getCellValueAsString(cell);
                    try {
                        glass.setGlassWidth(Double.parseDouble(widthStr));
                    } catch (NumberFormatException e) {
                        glass.setGlassWidth(0.0);
                    }
                }

                // 设置玻璃高度
                if (columnIndexMap.containsKey("glassHeight")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("glassHeight"));
                    String heightStr = getCellValueAsString(cell);
                    try {
                        glass.setGlassHeight(Double.parseDouble(heightStr));
                    } catch (NumberFormatException e) {
                        glass.setGlassHeight(0.0);
                    }
                }

                // 设置数量
                if (columnIndexMap.containsKey("quantity")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("quantity"));
                    String quantityStr = getCellValueAsString(cell);
                    try {
                        glass.setQuantity(Integer.parseInt(quantityStr));
                    } catch (NumberFormatException e) {
                        glass.setQuantity(1);
                    }
                }

                // 设置面积
                if (columnIndexMap.containsKey("area")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("area"));
                    String areaStr = getCellValueAsString(cell);
                    try {
                        glass.setArea(Double.parseDouble(areaStr));
                    } catch (NumberFormatException e) {
                        // 如果面积为空，尝试计算
                        if (glass.getGlassWidth() != null && glass.getGlassHeight() != null) {
                            glass.setArea(glass.getGlassWidth() * glass.getGlassHeight() / 1000000); // 转换为平方米
                        } else {
                            glass.setArea(0.0);
                        }
                    }
                } else {
                    // 如果没有面积列，尝试计算
                    if (glass.getGlassWidth() != null && glass.getGlassHeight() != null) {
                        glass.setArea(glass.getGlassWidth() * glass.getGlassHeight() / 1000000); // 转换为平方米
                    }
                }

                // 设置玻璃种类
                if (columnIndexMap.containsKey("glassType")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("glassType"));
                    glass.setGlassType(getCellValueAsString(cell));
                }

                // 设置创建和更新信息
                Date now = new Date();
                glass.setCreateTime(now);
                glass.setUpdateTime(now);

                // 如果宽度和高度都为0，则跳过
                if (glass.getGlassWidth() == 0.0 && glass.getGlassHeight() == 0.0) {
                    continue;
                }

                glassList.add(glass);
            }

            log.info("提取新格尔玻璃数据完成，共{}条记录", glassList.size());
            return glassList;
        } catch (Exception e) {
            log.error("提取新格尔玻璃数据失败", e);
            return glassList;
        }
    }

    /**
     * 从Excel中提取新格尔配件数据
     */
    private List<XgeAccessoriesTable> extractXgeAccessoriesData(Workbook workbook, SummaryFileParseResultVO result,
                                                                String orderId, Integer tenantId) {
        log.info("开始提取新格尔配件数据, orderId={}", orderId);

        // 获取订单明细ID
        ConcurrentHashMap<String, String> detailIdMap = new ConcurrentHashMap<>();

        List<XgeAccessoriesTable> accessoriesList = new ArrayList<>();

        try {
            // 默认使用第一个Sheet
            Sheet accessoriesSheet = workbook.getSheetAt(0);
            int sheetIndex = 0;

            log.info("使用第一个Sheet提取配件数据: index={}, name={}", sheetIndex, accessoriesSheet.getSheetName());

            // 找到标题行 窗号 编号 名称 规格 颜色 长度/数量
            int headerRowIndex = findHeaderRow(accessoriesSheet, new String[]{"窗号", "编号", "名称", "规格", "颜色", "长度/数量"});
            if (headerRowIndex < 0) {
                log.warn("未找到配件数据标题行");
                return accessoriesList;
            }

            // 解析标题行，找到各列对应的索引
            Row headerRow = accessoriesSheet.getRow(headerRowIndex);
            Map<String, Integer> columnIndexMap = new HashMap<>();

            for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell != null) {
                    String headerValue = getCellValueAsString(cell);
                    if (StringUtils.isNotBlank(headerValue)) {
                        if (headerValue.contains("窗号")) {
                            columnIndexMap.put("windowNo", i);
                        } else if (headerValue.contains("编号")) {
                            columnIndexMap.put("accessoryCode", i);
                        } else if (headerValue.contains("名称")) {
                            columnIndexMap.put("accessoryName", i);
                        } else if (headerValue.contains("规格")) {
                            columnIndexMap.put("specification", i);
                        } else if (headerValue.contains("颜色")) {
                            columnIndexMap.put("color", i);
                        } else if (headerValue.contains("长度/数量")) {
                            columnIndexMap.put("lengthQuantity", i);
                        } else if (headerValue.contains("数量")) {
                            columnIndexMap.put("quantity", i);
                        } else if (headerValue.contains("单位")) {
                            columnIndexMap.put("unit", i);
                        } else if (headerValue.contains("品牌")) {
                            columnIndexMap.put("brand", i);
                        } else if (headerValue.contains("部分") || headerValue.contains("位置")) {
                            columnIndexMap.put("partIndex", i);
                        }
                    }
                }
            }

            // 检查是否找到必要的列
            boolean hasIdentifier = columnIndexMap.containsKey("accessoryName") || columnIndexMap.containsKey("accessoryCode");
            boolean hasBasicInfo = columnIndexMap.containsKey("windowNo") || columnIndexMap.containsKey("specification");

            if (!hasIdentifier) {
                log.warn("配件数据中没有找到必要的列：名称或编号");
                return accessoriesList;
            }

            if (!hasBasicInfo) {
                log.warn("配件数据中没有找到基本信息列：窗号或规格");
            }

            // 提取数据行
            int dataRowIndex = headerRowIndex + 1;
            int serialNo = 1;

            // 读取数据直到文件末尾
            while (dataRowIndex <= accessoriesSheet.getLastRowNum()) {
                Row dataRow = accessoriesSheet.getRow(dataRowIndex);
                dataRowIndex++;

                if (dataRow == null) {
                    continue;
                }

                // 检查是否是空行
                boolean isEmptyRow = true;
                for (int i = 0; i < dataRow.getLastCellNum(); i++) {
                    Cell cell = dataRow.getCell(i);
                    if (cell != null && StringUtils.isNotBlank(getCellValueAsString(cell))) {
                        isEmptyRow = false;
                        break;
                    }
                }

                if (isEmptyRow) {
                    continue;
                }

                // 提取单元格数据
                XgeAccessoriesTable accessory = new XgeAccessoriesTable();
                accessory.setId(UUIDGenerator.generate());
                accessory.setTenantId(tenantId);
                accessory.setSerialNo(serialNo++);

                // 设置窗号
                if (columnIndexMap.containsKey("windowNo")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("windowNo"));
                    accessory.setWindowNo(getCellValueAsString(cell));
                    if (detailIdMap.containsKey(orderId + "-" + getCellValueAsString(cell))) {
                        accessory.setDetailId(detailIdMap.get(orderId + "-" + getCellValueAsString(cell)));
                    } else {
                        String detailId = getOrCreateDetailId(orderId, accessory.getWindowNo());
                        detailIdMap.put(orderId + "-" + getCellValueAsString(cell), detailId);
                        accessory.setDetailId(detailId);
                    }
                }

                // 设置配件编号
                if (columnIndexMap.containsKey("accessoryCode")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("accessoryCode"));
                    accessory.setAccessoryCode(getCellValueAsString(cell));
                }

                // 设置配件名称
                if (columnIndexMap.containsKey("accessoryName")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("accessoryName"));
                    accessory.setAccessoryName(getCellValueAsString(cell));
                }

                // 设置规格
                if (columnIndexMap.containsKey("specification")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("specification"));
                    accessory.setSpecification(getCellValueAsString(cell));
                }

                // 设置颜色
                if (columnIndexMap.containsKey("color")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("color"));
                    accessory.setColor(getCellValueAsString(cell));
                }

                // 设置长度/数量
                if (columnIndexMap.containsKey("lengthQuantity")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("lengthQuantity"));
                    accessory.setLengthQuantity(getCellValueAsString(cell));
                }

                // 设置数量
                if (columnIndexMap.containsKey("quantity")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("quantity"));
                    String quantityStr = getCellValueAsString(cell);
                    try {
                        accessory.setQuantity(Integer.parseInt(quantityStr));
                    } catch (NumberFormatException e) {
                        accessory.setQuantity(1);
                    }
                } else {
                    // 如果没有数量列，尝试从长度/数量列提取
                    if (StringUtils.isNotBlank(accessory.getLengthQuantity())) {
                        try {
                            accessory.setQuantity(Integer.parseInt(accessory.getLengthQuantity()));
                        } catch (NumberFormatException e) {
                            accessory.setQuantity(1);
                        }
                    } else {
                        accessory.setQuantity(1);
                    }
                }

                // 设置单位
                if (columnIndexMap.containsKey("unit")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("unit"));
                    accessory.setUnit(getCellValueAsString(cell));
                }

                // 设置品牌
                if (columnIndexMap.containsKey("brand")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("brand"));
                    accessory.setBrand(getCellValueAsString(cell));
                }

                // 设置部分索引
                if (columnIndexMap.containsKey("partIndex")) {
                    Cell cell = dataRow.getCell(columnIndexMap.get("partIndex"));
                    String partIndexStr = getCellValueAsString(cell);
                    try {
                        accessory.setPartIndex(Integer.parseInt(partIndexStr));
                    } catch (NumberFormatException e) {
                        accessory.setPartIndex(0);
                    }
                }

                // 设置创建和更新信息
                Date now = new Date();
                accessory.setCreateTime(now);
                accessory.setUpdateTime(now);

                // 如果配件名称和编号都为空，则跳过
                if (StringUtils.isBlank(accessory.getAccessoryName()) && StringUtils.isBlank(accessory.getAccessoryCode())) {
                    continue;
                }

                accessoriesList.add(accessory);
            }

            log.info("提取新格尔配件数据完成，共{}条记录", accessoriesList.size());
            return accessoriesList;
        } catch (Exception e) {
            log.error("提取新格尔配件数据失败", e);
            return accessoriesList;
        }
    }

    /**
     * 获取或创建订单明细ID
     * 如果订单已有明细，返回第一个明细ID；否则创建一个新的明细记录并返回ID
     */
    private String getOrCreateDetailId(String orderId, String windowNo) {
        log.info("获取或创建订单明细ID, orderId={}", orderId);

        if (StringUtils.isBlank(orderId)) {
            log.error("订单ID为空，无法获取或创建明细ID");
            return null;
        }

        // 查询订单关联的明细ID 根据订单id和窗号查询
        ProductSalesOrderDetail detail = productSalesOrderDetailMapper.selectOne(new QueryWrapper<ProductSalesOrderDetail>()
                .eq("order_id", orderId).eq("window_no", windowNo));

        if (detail != null) {
            return detail.getId();
        }

        return UUIDGenerator.generate();
    }

    /**
     * 在Excel表格中查找包含指定关键字的标题行
     *
     * @param sheet    Excel表格
     * @param keywords 要查找的关键字数组
     * @return 找到的行索引，如果未找到则返回-1
     */
    private int findHeaderRow(Sheet sheet, String[] keywords) {
        log.debug("开始在Sheet中查找标题行，关键字: {}", String.join(", ", keywords));

        // 检查所有行
        for (int i = 0; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) continue;

            // 创建一个标记数组，用于记录每个关键字是否找到
            boolean[] keywordFound = new boolean[keywords.length];

            for (int j = 0; j < row.getLastCellNum(); j++) {
                Cell cell = row.getCell(j);
                if (cell == null) continue;

                String cellValue = getCellValueAsString(cell);
                if (StringUtils.isBlank(cellValue)) continue;

                // 检查是否包含任一关键字
                for (int k = 0; k < keywords.length; k++) {
                    if (!keywordFound[k] && cellValue.contains(keywords[k])) {
                        keywordFound[k] = true;
                    }
                }
            }

            // 检查是否所有关键字都找到了
            boolean allKeywordsFound = true;
            for (boolean found : keywordFound) {
                if (!found) {
                    allKeywordsFound = false;
                    break;
                }
            }

            if (allKeywordsFound) {
                log.debug("在第{}行找到标题行，包含所有关键字", i);
                return i;
            }
        }

        log.debug("未找到包含所有关键字的标题行");
        return -1;
    }

    /**
     * 处理窗户汇总文件
     */
    private void dealWindowFile(Workbook workbook, SummaryFileParseResultVO result, String orderId, Integer tenantId) {
        log.info("开始处理窗户汇总文件，orderId={}", orderId);

        try {
            // 使用线程池并行提取型材、玻璃和配件信息
            // 创建线程安全的副本
            final Workbook finalWorkbook = workbook;
            final SummaryFileParseResultVO finalResult = result;
            final String finalOrderId = orderId;
            final Integer finalTenantId = tenantId;

            log.info("开始并行提取窗户型材、玻璃和配件数据，所有数据都在第一个Sheet中");

            // 使用指定的线程池执行任务
            CompletableFuture<List<XgeProfileSizeTable>> xgeProfileFuture = CompletableFuture
                    .supplyAsync(() -> extractXgeProfileData(finalWorkbook, finalResult, finalOrderId, finalTenantId), taskExecutor);

            CompletableFuture<List<XgeGlassSizeTable>> xgeGlassFuture = CompletableFuture
                    .supplyAsync(() -> extractXgeGlassData(finalWorkbook, finalResult, finalOrderId, finalTenantId), taskExecutor);

            CompletableFuture<List<XgeAccessoriesTable>> xgeAccessoriesFuture = CompletableFuture
                    .supplyAsync(() -> extractXgeAccessoriesData(finalWorkbook, finalResult, finalOrderId, finalTenantId), taskExecutor);

            // 等待所有任务完成并设置超时
            CompletableFuture<Void> allFutures = CompletableFuture.allOf(
                    xgeProfileFuture, xgeGlassFuture, xgeAccessoriesFuture
            );

            try {
                // 设置总体超时
                allFutures.get(120, TimeUnit.SECONDS);

                // 获取各个任务结果
                List<XgeProfileSizeTable> xgeProfileList = xgeProfileFuture.get();
                List<XgeGlassSizeTable> xgeGlassList = xgeGlassFuture.get();
                List<XgeAccessoriesTable> xgeAccessoriesList = xgeAccessoriesFuture.get();

                result.setXgeProfileList(xgeProfileList);
                result.setXgeGlassList(xgeGlassList);
                result.setXgeAccessoriesList(xgeAccessoriesList);

                // 设置数量统计
                result.setProfileCount(xgeProfileList != null ? xgeProfileList.size() : 0);
                result.setGlassCount(xgeGlassList != null ? xgeGlassList.size() : 0);
                result.setAccessoriesCount(xgeAccessoriesList != null ? xgeAccessoriesList.size() : 0);

                log.info("窗户汇总文件处理成功，型材：{}条，玻璃：{}条，配件：{}条",
                        result.getProfileCount(), result.getGlassCount(), result.getAccessoriesCount());

            } catch (TimeoutException e) {
                // 取消所有未完成的任务
                xgeProfileFuture.cancel(true);
                xgeGlassFuture.cancel(true);
                xgeAccessoriesFuture.cancel(true);

                log.error("提取窗户数据超时", e);
                result.setMessage("提取窗户数据超时，请检查Excel文件格式");
            } catch (Exception e) {
                log.error("提取窗户数据失败", e);
                result.setMessage("提取窗户数据失败: " + e.getMessage());
            }
        } catch (Exception e) {
            log.error("处理窗户汇总文件失败", e);
            result.setMessage("处理窗户汇总文件失败: " + e.getMessage());
        }
    }



//    private void extractOrderInfoForDoor(Workbook workbook, SummaryFileParseResultVO result) {
//        //门的汇总单返回的是订单明细编号
//        Sheet sheet = workbook.getSheetAt(0);
//        Row row = sheet.getRow(1);
//        Cell cell = row.getCell(9);
//        result.setOrderNo(getCellValueAsString(cell));
//    }
//    /**
//     * 处理门汇总文件
//     * 根据图片中的门汇总文件模板解析门的数据
//     */
//    private void dealDoorFile(Workbook workbook, SummaryFileParseResultVO result, String orderId, Integer tenantId) {
//        log.info("开始处理门汇总文件，orderId={}", orderId);
//
//        try {
//            // 门汇总文件的数据结构与窗户不同，需要专门的解析逻辑
//            // 根据图片显示的门汇总文件模板，包含：物料名称、物料编码、颜色、厚度、支长、数量、可用库存、订单号、终端地址、材料系列
//
//            // 使用线程池并行提取门的型材、玻璃和配件信息
//            final Workbook finalWorkbook = workbook;
//            final SummaryFileParseResultVO finalResult = result;
//            final String finalOrderId = orderId;
//            final Integer finalTenantId = tenantId;
//
//            log.info("开始并行提取门型材、玻璃和配件数据");
//
//            Sheet sheet = finalWorkbook.getSheet(String.valueOf(0));
//            //逐行获取型材汇总数据  配件数据等待完善
//            List<XgeProfileSizeTable> doorProfileList = new ArrayList<>();
//            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
//                Row row = sheet.getRow(i);
//                if (row != null) {
//                    XgeProfileSizeTable xgeProfileSizeTable = new XgeProfileSizeTable();
//                    String materialName = row.getCell(0).getStringCellValue();
//                    String materialCode = row.getCell(1).getStringCellValue();
//                    String color = row.getCell(2).getStringCellValue();
//                    String thickness = row.getCell(3).getStringCellValue();//厚度
//                    String length = row.getCell(4).getStringCellValue();
//                    String quantity = row.getCell(5).getStringCellValue();
//                    String windowNo = row.getCell(6).getStringCellValue();
//                    xgeProfileSizeTable.setProfileName(materialName)
//                            .setProfileCode(materialCode)
//                            .setColor(color)
//                            .setThickness(Double.valueOf(thickness))
//                            .setLength(Double.valueOf(length))
//                            .setQuantity(Integer.valueOf(quantity))
//                            .setCreateTime(new Date());
//                    //获取明细ID
//                    doorProfileList.add(xgeProfileSizeTable);
//                }
//            }
//
//            try {
//                result.setXgeProfileList(doorProfileList);
//                result.setXgeGlassList(new ArrayList<>());
//                result.setXgeAccessoriesList(new ArrayList<>());
//
//                // 设置数量统计
//                result.setProfileCount(doorProfileList != null ? doorProfileList.size() : 0);
//                result.setGlassCount(0);
//                result.setAccessoriesCount(0);
//
//            } catch (Exception e) {
//                log.error("提取门数据失败", e);
//                result.setMessage("提取门数据失败: " + e.getMessage());
//            }
//        } catch (Exception e) {
//            log.error("处理门汇总文件失败", e);
//            result.setMessage("处理门汇总文件失败: " + e.getMessage());
//        }
//    }
}